import { useState } from 'react';
import Viewer from 'react-viewer';

import { IImageElement } from 'state/element';

import ImageFrame from './frame';

interface Props {
  element: IImageElement;
}

//点击下载逻辑
// const handleImageClick = (name: string, src: string) => {
//   const link = document.createElement('a');
//   link.href = src;
//   link.target = '_blank';
//   link.download = name;
//   link.style.display = 'none';
//   document.body.appendChild(link);
//   link.click();
//   document.body.removeChild(link);
// };

export default function ImageElement({ element }: Props) {
  const src = element.url || URL.createObjectURL(new Blob([element.content!]));
  const className = `${element.display}-image`;
  const [open, setOpen] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');
  //点击预览图片
  const handleImageClick = (name: string, src: string) => {
    setPreviewUrl(src);
    setOpen(true);
  };
  return (
    <ImageFrame>
      <img
        className={className}
        src={src}
        onClick={() => {
          const name = `${element.name}.png`;
          handleImageClick(name, src);
        }}
        style={{
          objectFit: 'cover',
          maxWidth: '100%',
          margin: 'auto',
          height: 'auto',
          display: 'block',
          cursor: 'pointer'
        }}
        alt={element.name}
        loading="lazy"
      />
      <Viewer
        visible={open}
        noNavbar={true}
        showTotal={false}
        noImgDetails={true}
        customToolbar={(toolbars) => {
          return toolbars.concat([
            {
              key: 'download-img',
              render: (
                <div>
                  <i className="react-viewer-icon react-viewer-icon-download"></i>
                </div>
              ),
              onClick: (activeImage) => {
                const link = document.createElement('a');
                link.href = activeImage.src;
                link.target = '_blank';
                link.download = `${element.name || 'images'}.png`;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
              }
            }
          ]);
        }}
        onClose={() => {
          setOpen(false);
        }}
        images={[{ src: previewUrl, downloadUrl: previewUrl }]}
      />
    </ImageFrame>
  );
}
